<!--
 @Date: 2025-06-30 17:40:03
 * @LastEditTime: 2025-07-15 10:48:43
-->
<template>
    <div class="deploy-form-plain-wrapper">
      <Form  layout="horizontal" class="deploy-form-plain" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }" :model="form" :rules="rules" ref="formRef">
        <FormItem label="任务名称：" name="flowName" required>
          <Input v-model:value="form.flowName" placeholder="请输入任务名称" />
        </FormItem>
        <FormItem label="任务描述：" name="flowDesc">
          <Input v-model:value="form.flowDesc" placeholder="请输入任务描述" />
        </FormItem>
        <FormItem label="选择采集任务：" name="collectFlowId" required>
          <div style="display: flex; gap: 8px;">
            <Select v-model:value="form.collectFlowId" placeholder="请选择评估任务" style="flex:1;"  @change="changeGather">
              <Select.Option :value="item.flowId" v-for="item in gatherList" :key="item.flowId">{{item.flowName}}</Select.Option>
            </Select>
          </div>
        </FormItem>
        <FormItem label="源数据源：" required class="source-form-item">
          <Row :gutter="16">
            <Col :span="11">
            <FormItem name="sourceType" style="flex:1; margin-bottom:0;">
              <Select v-model:value="form.sourceType" placeholder="请选择数据源类型" @change="changeSourceType">
                <Select.Option :value="item.dbConfName" v-for="item in sourceTypeList" :key="item.dbConfId">{{item.dbConfName}}</Select.Option>
  
              
              </Select>
            </FormItem>
            </Col>
            <Col :span="11">
            <FormItem name="source" style="flex:1; margin-bottom:0;">
              <Select v-model:value="form.sourceId" placeholder="请选择数据源" @dropdownVisibleChange="getDataSourcePageInfo">
                <Select.Option 
                :value="item.db_id" 
                :filter-option="filterOption"
                v-for="item in sourceList" 
                :key="item.db_id"
                :label="item.db_alias_name"
                >
                {{item.db_alias_name}}
                </Select.Option>
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0" />
                  <div
                    style="padding: 4px 8px; width: 100%"
                    @mousedown.prevent
                    @click.stop
                  >
                    <a-flex
                      style="width: 100%; padding-left: 30px"
                      horizontal
                      justify="center"
                      align="center"
                    >
                      <span style="line-height: 35px">没找到？</span>
                      <a-button type="text" @click="openAddGroups">
                        <template #icon>
                          <plus-outlined />
                        </template>
                        创建数据
                      </a-button>
                    </a-flex>
                  </div>
                </template> 
              </Select>
            </FormItem>
            </Col>
            <Col :span="2">   
            <Button type="link" @click="linkTest()">连接测试</Button>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="程序执行节点：" name="macId" required>
          <div style="display: flex; gap: 8px;">
            <Select v-model:value="form.macId" placeholder="选择程序运行的主机" style="flex:1;">
              <Select.Option :value="item.mac_id" v-for="item in hostList" :key="item.host_ip">{{item.host_name}}</Select.Option>
              <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0" />
                  <div
                    style="padding: 4px 8px; width: 100%"
                    @mousedown.prevent
                    @click.stop
                  >
                    <a-flex
                      style="width: 100%; padding-left: 30px"
                      horizontal
                      justify="center"
                      align="center"
                    >
                      <span style="line-height: 35px">没找到？</span>
                      <Button type="text" @click="openaddHost">
                        <template #icon>
                          <plus-outlined />
                        </template>
                        添加主机
                      </Button>
                    </a-flex>
                  </div>
                </template> 
            </Select>
            <Button type="link" @click="testLinkhost">连接测试</Button>
          </div>
        </FormItem>
        <FormItem label="选择迁移范围：" name="targetKeys" required>
          <div class="dev-section" v-if="form.collectFlowId">
            <a-checkbox class="dev-checkbox">整个数据源迁移</a-checkbox>
            <div class="dev-transfer-box">
              <a-transfer
                v-model:target-keys="form.targetKeys"
                :data-source="mapping"
                :titles="['可选项', '已选项']"
                :render="item => item.operateResources"
                @change="handleChange"
                :list-style="{ width: '400px', height: '400px' }"
              />
            </div>
          </div>
        </FormItem>
      </Form>
    </div>
    <div class="flex justify-center">
          <!-- <a-button type="primary" @click="prev" style="margin-right: 10px;">上一步</a-button> -->
          <a-button type="primary" @click="next">下一步</a-button>
          <!-- 生成图表 -->
  
         </div>
      <!-- 添加数据源 -->
      <addSourceForm
        v-if="openGroups"
        :open="openGroups"
        @update:open="closeGroups"
      />
      <addEditHost ref="addEditHostRef" @getTabData="getTabData" :ot="$t"></addEditHost>
  </template>
  
  <script setup>
  import { ref, reactive,defineExpose,onMounted,defineComponent,defineEmits } from 'vue';
  import { Form,FormItem, Input, Select, Button ,Row,Col,message} from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import * as http from '@/api/flow/createTask';
  import * as flowhttp from '@/api/flow/index';
  import { useStore } from 'vuex';
  import addEditHost from "@DSG/components/AddHost"
  import addSourceForm from "@/components/addSourceForm/index";
  const store = useStore();
  const VNodes = defineComponent({
    props: {
      vnodes: {
        type: Object,
        required: true,
      },
    },
    render () {
      return this.vnodes;
    },
  });
  const openGroups = ref(false); //添加组
  const formState = reactive({
    flowName: "",
    flowGroupId: undefined,
    flowDesc: "",
    flowType: 1,
    taskStype: undefined,
    taskTtype: undefined,
    taskSRC: undefined,
    taskSRCname: undefined,
    taskTAR: undefined,
    taskTARname: undefined,
    taskTarList: [0],
    type0: undefined,
    srcData0: undefined,
    taskName0: undefined,
    dbCustomName0: undefined,
    deployModel: 1,
    host: undefined,
    srcHost: undefined,
    tarHost: undefined,
    srcNodeNumber: undefined,
    isDeployBackflow: false,
    backFlowMode: 1,
  });
  const formRef = ref();
  const form = reactive({
    flowName: '',
    flowDesc: '',
    sourceType: '',
    sourceId: '',
    collectFlowId: '',
    targetKeys: [],
    macId: '',
  });
  const mapping = ref([])
  const testLinkhost = async () => {
    const selectedHost = hostList.value.find(host => host.mac_id === form.macId);
    if (!selectedHost) {
      message.warning('请先选择主机');
      return;
    }
    
    // try {
      const params = {
        ...selectedHost,
        userID: sessionStorage.getItem("userId")
      };
      
      const res = await flowhttp.verifyHost(params);
      if (res.code === "000000") {
        message.success('连接测试成功');
      } else {
        message.error('连接测试失败！');
      }
  };
  //连接测试
  const linkTest = async () => {
    linkCommon()
  };
  //大数据连接测试
  const biglinkCommon = async () => {
  
  const item = typeDatas.value.find(
    (e) =>
      e.db_id == formState[oProps.dataSource] ||
      e.db_alias_name == formState[oProps.dataSource]
  );
  
  // item["userID"] = sessionStorage.getItem("userId");
  // item.db_type = formState[oProps.type].split("|")[1];
  console.log(newbigdata.value, newgroupId.value, 'typeDatastypeDatasssssssssssss')
  let resBody = {}
  resBody.clusterType = newbigdata.value.clusterType;
  resBody.clusterVersion = newbigdata.value.clusterVersion;
  resBody.clusterAliasName = newbigdata.value.clusterAliasName;
  resBody.clusterFilePath = newbigdata.value.clusterFilePath;
  resBody.kerberos = newbigdata.value.kerberos;
  if (newbigdata.value.isdatahub) {
    resBody.isdatahub = newbigdata.value.isdatahub;
  }
  resBody.userKeyPath = newbigdata.value.userKeyPath;
  resBody.kerberosKeyPath = newbigdata.value.kerberosKeyPath;
  resBody.verifyUser = newbigdata.value.verifyUser;
  resBody.verifyRegionName = newbigdata.value.verifyRegionName;
  resBody.dataValue = newbigdata.value.dataValue;
  resBody.uploadPath = newbigdata.value.uploadpa;
  resBody.serviceName = newbigdata.value.serviceName;
  // if(this.hostS[0].hostIp || this.hostS[0].hostName){
  //   resBody.mapHost = JSON.stringify(this.hostS);
  // }
  
  
  const res = await http.startClusterConfig(resBody);
  if (res.code == "000000") {
    message.success($t('baseForm.sourceTargetItem.testSuccess'));
    // saveDataSourceInfo(params);
  } else {
    message.error($t('baseForm.sourceTargetItem.testFail'));
  }
  };
  const linkCommon = async () => {
    console.log(form.sourceId, 'form.sourceId')
    const item = sourceList.value.find(
      (e) =>
        e.db_id === form.sourceId
    );
  
    item["userID"] = sessionStorage.getItem("userId");
    item.isTnsNameUpdate = false
    const res = await flowhttp.validatorDataSource({ ...item });
    if (res.code == "000000") {
      message.success('连接测试成功');
    } else {
      message.error('连接测试失败！');
    }
  };
  // 关闭弹框
  const closeGroups = () => {
    openGroups.value = false;
  };
  
  const addEditHostRef = ref(null)
  const openaddHost = () => {
    // openHost.value = true;
    addEditHostRef.value.openAdd()
  };
  const handleChange = (targetKeys, direction, moveKeys) => {
    form.targetKeys = targetKeys
    mapping.value.forEach(item => {
      if(form.targetKeys.includes(item.operateResources)){
        item.isSelect = 1
      }else{
        item.isSelect = 0
      }
    })
  };
  // 查询获取数据
  const queryConfig = async () => {
    let params = {
      flowId:form.collectFlowId,
    }
    let res = await http.queryConfig(params)
    try {
      if(res.code === '000000'){
        mapping.value = res.data.mapping
        mapping.value.forEach(item => {
          item.key = item.operateResources
          if(item.isSelect === 1){
            form.targetKeys.push(item.operateResources)
          }
        })
      }
    } catch (error) {
      console.log(error)
    }
  }
  const gatherList = ref([])
  // 获取迁移任务
  const getGatherList = async () => {
    let params = {
      flowType:1,
      flowStatus:3,
      offset:1,
      limit:1000
    }
    let res = await http.getGatherList(params)
    try {
      if(res.code === '000000'){
        gatherList.value = res.data.records
      }
    } catch (error) {
      console.log(error)
    }
  }
  const changeGather = (value) => {
    queryConfig()
    console.log(value,'value')
  }
  const sourceTypeList = ref([]);
  const hostList = ref([]);
  const sourceList = ref([]);
  const selectRowSourceType = ref({});
  const filterOption = (input, option) => {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  const rules = {
    flowName: [
      { required: true, message: '请输入任务名称', trigger: 'blur' }
    ],
    sourceType: [
      { required: true, message: '请选择数据源类型', trigger: 'change' }
    ],
    sourceId: [
      { required: true, message: '请选择数据源', trigger: 'change' }
    ],
  
    collectFlowId: [
      { required: true, message: '请选择采集任务', trigger: 'change' }
    ],
    targetKeys: [
      { required: true, message: '请选择迁移范围', trigger: 'change' }
    ],
    macId: [
      { required: true, message: '请选择程序执行节点', trigger: 'change' }
    ]
  };
  const next =async () => {
    let res = await save()
    console.log(res,'res')
    if(res){
      emit('next')
    }
  }
  
  const save = () => {
    console.log('save')
   return formRef.value.validate().then(async res => {
  
     
      let status = await  MigrationSaveCMFlowInfo()
  
      if(status.code == '000000'){
        return true
      }else{
        message.error(status.msg)
        return true
      }
    }).catch(err => {
     return false
    });
  };
  const openAddGroups = () => {
    openGroups.value = true;
  };
  const changeSourceType = (value) => {
    selectRowSourceType.value = sourceTypeList.value.find(item => item.dbConfName == value);
    form.sourceId=''
  };
  const MigrationSaveCMFlowInfo =async () => {
    let params = {
      flowId:store.state.taskInfo.migrationFlowId,
      flowType:2,
      dbId:form.sourceId,
      macId:form.macId,
      flowName: form.flowName,
      flowDesc: form.flowDesc,
      userId:window.sessionStorage.getItem("userId"),
      collectFlowId:form.collectFlowId,
      migrationScopeJson:JSON.stringify(mapping.value)
    }
    let res = await http.MigrationSaveCMFlowInfo(params);
    console.log(res);
    return res
  };
  
  // 获取数据源类型
  const getDataBaseTypeInfo = async () => {
    let params = {
      userID:window.sessionStorage.getItem("userId"),
    }
    let res = await http.getDataBaseTypeInfo(params);
    try {
      sourceTypeList.value = res.data;
    } catch (error) {
      console.log(error);
      message.error(error);
    }
  };
  // 获取数据源列表
  const getDataSourcePageInfo = async () => {
    let params = {
      userID:window.sessionStorage.getItem("userId"),
      groupId:selectRowSourceType.value.groupId,
      db_type:selectRowSourceType.value.dbConfName,
      userGroupId: sessionStorage.getItem("userGid"),
      engineID:''
      
    }
    let res = await http.getDataSourcePageInfo(params);
    try {
      sourceList.value = res.data.rows;
    } catch (error) {
      console.log(error);
      message.error(error);
    }
  };
  // 获取主机列表
  const queryAllHostInfo = async () => {
    let params = {
      userID:window.sessionStorage.getItem("userId"),
    }
    let res = await http.queryAllHostInfo(params);
    try {
      hostList.value = res.data.rows;
    } catch (error) {
      console.log(error);
      message.error(error);
    }
  };
  const emit = defineEmits(['save','next','prev'])
  // 获取回显信息
  const queryCMFlowInfo = async () => {
    let params = {
      flowId:store.state.taskInfo.flowId,
    }
    let res = await http.queryCMFlowInfo(params);
    try{
      if(res.code == '000000' && res.data){
        form.flowName = res.data.flowName
        form.flowDesc = res.data.flowDesc
        form.sourceType = res.data.reserve4
        form.sourceId = res.data.dbId
        form.targetTypes = res.data.reserve2.split(',')
      }
    }catch(error){
      console.log(error);
      message.error(error);
    }
  }
  onMounted(() => {
    console.log("store.state.taskInfo:nnnnnnnnnnnnnnn ", store.state.taskInfo);
    if(store.state.taskInfo.migrationFlowId){
      queryCMFlowInfo()
    }else{
      store.commit('setMigrationFlowId',new Date().getTime());
    }
    getDataBaseTypeInfo()
    getGatherList()
    queryAllHostInfo()
  });
  defineExpose({
    save
  });
  </script>
  
  <style scoped>
  .deploy-form-plain-wrapper {
    width: 100%;
    min-height: 480px;
    padding: 40px 0 24px 0;
    display: flex;
    justify-content: center;
  }
  .deploy-form-plain {
    min-width: 340px;
    max-width: 700px;
    width: 100%;
    margin-left: 0;
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    padding: 0;
  }
  :deep(.ant-form-item-label > label) {
    font-weight: 500;
    font-size: 15px;
  }
  .source-form-item{
      margin-bottom: 0 !important;
    }
  @media (max-width: 900px) {
    .deploy-form-plain {
      min-width: 0;
      max-width: 100vw;
      margin-left: 0;
      padding: 0 4vw;
    }
    .deploy-form-plain-wrapper {
      justify-content: center;
    }
    
  }
  </style>